package cn.xzz.pethome.dept.service.impl;

import cn.xzz.pethome.dept.domain.Department;
import cn.xzz.pethome.dept.mapper.DepartmentMapper;
import cn.xzz.pethome.dept.query.DeptQuery;
import cn.xzz.pethome.dept.service.IDeptService;
import cn.xzz.pethome.share.utils.PageCount;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class DeptServiceImpl implements IDeptService {
    @Autowired
    private DepartmentMapper departmentMapper;

    //分页查询
    @Override
    public PageCount<Department> getPageCount(DeptQuery query) {
        PageCount<Department> departmentPageCount = new PageCount<>();
        departmentPageCount.setCount(departmentMapper.findcount(query));
        departmentPageCount.setDeptlist(departmentMapper.findAll(query));
        return departmentPageCount;
    }

    @Override
    public Department findById(Long id) {
        return departmentMapper.findById(id);
    }

    @Transactional
    @Override
    public void adddept(Department department) {
            departmentMapper.adddept(department);
    }

    @Transactional
    @Override
    public void updatedept(Department department) {
            departmentMapper.updatedept(department);
    }

    @Transactional
    @Override
    public void delete(Long id) {
            departmentMapper.delete(id);
    }

    @Override
    @Transactional
    public void batchdeletedept(List<Long> ids) {
        departmentMapper.batchdeletedept(ids);
    }

    @Override
    public List<Department> getTree() {
        //第一步查询所有部门
        List<Department> deptAll = departmentMapper.findDeptAll();
        //专门用装顶级部门的
        List<Department> firstDept = new ArrayList<>();
        for (Department department : deptAll) {
            //判断parent_id == null 就是顶级部门
            if(department.getParent_id() == null){
                firstDept.add(department);
            }else{
                //不是顶级部门
                for (Department parentDept : deptAll) {
                    //找自己的爹
                    if(department.getParent_id().equals(parentDept.getId())){
                        //把自己放入到爹里面的children
                        parentDept.getChildren().add(department);
                    }
                }
            }
        }
        return firstDept;
    }
}
